package org.example.struct.array;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author liyishan
 * @date 2023/8/1 10:15
 * @apiNote
 */

public class Test00219ContainsNearbyDuplicate {
    public static void main(String[] args) {
        int[] a = new int[]{1, -1, 1, -1, 1, -1,1};
        boolean count = test(a,3);
        System.out.println(count + "  array:" + JSON.toJSON(a));
    }

    public static boolean test(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i < nums.length;i++){
            if(map.containsKey(nums[i]) && i- map.get(nums[i]) <= k){
                return true;
            }else{
                map.put(nums[i],i);
            }
        }
        return false;
    }

    public static boolean test1(int[] nums, int k) {
        Set<Integer> set = new HashSet<>();
        for(int i = 0;i<nums.length;i++){
            if(i>k){
                set.remove(nums[i-k-1]);
            }
            if(!set.add(nums[i])) {
                return true;
            }
        }
        return false;
    }

}
